package epg51zmt

import (
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"github.com/gocolly/colly"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/text/gregex"
	"strings"
	"time"
	"uni-crawl-frame/core"
	"uni-crawl-frame/db/mysql/model/entity"
	"uni-crawl-frame/service/crawl/replayservice"
)

//海外epg免费或收费提供的默认XML格式解析
type Epg51zmt struct {
	*core.AbstractCrawlReplayUrl
}

// CreateProgram eg: http://epg.51zmt.top:8000/api/i/?ch=CCTV1
// FindProgrameg:http://epg.51zmt.top:8000
func (receiver *Epg51zmt) CreateProgram(replayConfig *entity.CmsCrawlReplayConfig, manifestTask *entity.CmsCrawlReplayManifestTask) {
	//g.Dump(replayConfig)
	nowtime := gtime.Now().Format("Y-m-d")
	url := fmt.Sprintf("%s&date=%s", replayConfig.SeedUrl, nowtime)
	g.Log().Infof(gctx.GetInitCtx(), "epg51zmt start ->%v", url)
	coll := colly.NewCollector()
	todayTime := gtime.Now()
	todayTimeStr := todayTime.Format("Y-m-d")
	var epgItem []*ListItem
	coll.OnResponse(func(response *colly.Response) {
		doc, err := goquery.NewDocumentFromReader(strings.NewReader(string(response.Body)))
		if err != nil {
			g.Log().Debugf(gctx.GetInitCtx(), "解析HTML出错:%v", err)
			return
		}
		li := doc.Find("ul li")
		li.Each(func(i int, selection *goquery.Selection) {
			//g.Dump(selection.Text())
			str := strings.Replace(selection.Text(), " ", "", -1)
			timeAndTitle, _ := gregex.MatchString("(\\d{2}:\\d{2})(.*)", str)
			if timeAndTitle != nil {
				//数据长度过小数据不对跳过
				if len(timeAndTitle) < 2 {
					return
				}
			} else {
				//正则拿到空跳过
				return
			}
			startTime := timeAndTitle[1]
			title := timeAndTitle[2]
			nowItem := &ListItem{
				StartTime: fmt.Sprintf("%s %s:00", todayTimeStr, startTime),
				Title:     title,
			}
			epgItem = append(epgItem, nowItem)
		})

		//无结束时间的节目重新计算一下节目单时间
		for i := 0; i < len(epgItem); i++ {
			if i == len(epgItem)-1 {
				//最后一项处理
				//	最后一个节目的结束时间暂定为第一个节目接开始时间+1天
				endTimeDay := gtime.New(epgItem[0].StartTime).Add(time.Hour * 24)
				epgItem[i].EndTime = endTimeDay.Format("Y-m-d H:i:s")
			} else {
				//当前节目的结束时间为下一个节目的开始时间
				epgItem[i].EndTime = epgItem[i+1].StartTime
			}
			programTask := new(entity.CmsCrawlReplayProgramTask)
			programTask.ManifestId = manifestTask.Id
			programTask.ConfigId = replayConfig.Id
			programTask.ProgramNo = gtime.New(epgItem[i].StartTime).TimestampMicroStr()
			programTask.ProgramName = epgItem[i].Title
			programTask.ProgramStartTime = gtime.New(epgItem[i].StartTime)
			programTask.ProgramEndTime = gtime.New(epgItem[i].EndTime)
			programTask.CreateTime = gtime.Now()
			programTask.CrawlStatus = replayservice.ProgramTaskInit
			programTask.HostIp = replayConfig.Host
			replayservice.CheckAndSave(programTask)
			//dbProgramTask := replay.GetProgramTask(programTask)

		}
		//g.Dump(epgItem)

	})
	_ = coll.Visit(url)

}

type ListItem struct {
	Title     string `json:"title"`
	StartTime string `json:"startTime"`
	EndTime   string `json:"endTime"`
}
